<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Users;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Mews\Captcha\Facades\Captcha;


/**
 * 登录相关
 * Class CateController
 * @package App\Http\Controllers
 */
class AuthController extends Controller {

    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function login(Request $request){
        try {
            $credentials = $request->only('username','password','captcha','captchaKey');
            //判断用户是否存在
            $user = Users::where('openid',$credentials['username'])->where('is_admin',Users::ADMIN_1)->first();
            if(!$user || strlen($credentials['username'])>15){
                return $this->returnJson(1,'管理员账户不存在');
            }
            $client = new Client();
            $url = request()->root() . '/oauth/token';
            $params = array_merge(config('passport.proxy'), [
                'username' => $credentials['username'],
                'password' => $credentials['password'],
            ]);
            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            $user->update(['login_at'=>Carbon::now()]);
            return $this->returnJson(0,'',$token_info);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return $this->returnJson(1,'密码输入错误');
        }
    }


    /**
     * 刷新token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function refresh(Request $request){
        try {
            $refreshToken = $request->get('refresh_token','');
            if(empty($refreshToken)){
                return $this->returnJson(1, '参数错误');
            }
            $client = new Client();
            $url = request()->root() . '/oauth/token';
            $params = array_merge(config('passport.refresh'), [
                'refresh_token' => $refreshToken,
            ]);
            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            return $this->returnJson(0,'',$token_info);
        } catch (\Exception $e) {
            return $this->returnJson(1, '刷新失败');
        }
    }

    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function logout(){
        try {
            if (auth()->guard('api')->check()) {
                auth()->guard('api')->user()->token()->delete();
                return $this->returnJson(0,'登出成功,页面即将跳转...');
            }
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }

    }

    public function captcha(){
        try {
            $captcha = Captcha::create('default', true);
            return $this->returnJson(0,'',$captcha);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

}
